/**
 * meilele.com Inc.
 * Copyright (c) 2004-2016 All Rights Reserved.
 */
package com.gpagers.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.junit.Test;

import com.gpagers.core.ObjectRef;

/**
 * 
 * @author liuzijie@meilele.com
 * @version $Id: FileSDK.java, v 0.1 2016年5月9日 上午11:01:55 liuzijie@meilele.com Exp $
 */
public class FileSDK {

    @Test
    public void test() {
        System.out.println(readFileByLines());
    }

    /**
     * 以行为单位读取文件，常用于读面向行的格式化文件
     */
    @SuppressWarnings("finally")
    public static List<String> readFileByLines() {
        List<String> result = new ArrayList<String>();
        BufferedReader reader = null;
        File file = new File(ObjectRef.dataFile);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        try {
            reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(ObjectRef.dataFile), "UTF-8"));
            String tempString = null;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                result.add(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
            return result;
        }
    }

    public static void writeLog(List<String> results) {
        try {
            String path = ObjectRef.dataFile;
            File file = new File(path);
            if (!file.exists())
                file.createNewFile();
            FileOutputStream out = new FileOutputStream(file, false); //如果追加方式用true        
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < results.size(); i++) {
                sb.append(results.get(i));
                if (i != results.size() - 1)
                    sb.append("\r\n");
            }
            out.write(sb.toString().getBytes("utf-8"));//注意需要转换对应的字符集
            out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
